# coding: utf-8

import json
import os
import uuid
from io import BytesIO

import time

from binstar_client.commands import logout
from flask import request, make_response, Response
from fraMail.framail import FraMail

import QRcodeOper
from fralog.FraLog import getFileLog
from exceptions.fra_exception import FraException
from settings import *
from dbproxy.dbproxy import *
from PIL import Image
from globalsettings import CUR_MODE

if CUR_MODE == 'dev':
    from globalsettings_dev import *
else:
    from globalsettings_prod import *
# from globalsettings import COMBINE_HOSTNAME, COMBINE_LONGURL, COMBINE_SHORTURL, COMBINE_STAT
log = getFileLog()


class HRPayinvoice(object):
    """
    hr支付开票模块
    """
    table_name = 'invoices_collection'

    def __init__(self):
        super(HRPayinvoice, self).__init__()
        self.db_proxy = DBProxy(db=mongo)

    def get_surveys_url(self, user_id):
        """
        根据user_id查询第一个问卷信息
        :param pagesize
        :param page
        :return:
        """
        log.debug('查询')
        log.debug('查询报告模板内容')
        user_item = self.db_proxy.query_one(table='t_user_product', query={'user_id': user_id})  # 获取公司名称或公司guid
        if user_item['count'] > 0:
            temp_company_id = user_item['data'][0]['company_id']
            company_item = self.db_proxy.query_one(table='company_collection', query={'company_name': temp_company_id})
            if company_item.get('count') > 0:
                company_id = company_item['data'][0]['guid']
            else:
                company_id = temp_company_id
            companyname_item = self.db_proxy.query_one(table='company_collection', query={'guid': company_id})
            company_name = companyname_item['data'][0]['company_name']
            ret1 = self.db_proxy.query_one(table='surveys_collection', query={'company_id': company_name})
            if ret1.get('count') > 0:
                log.debug('查询成功返回')
                return ret1
            else:
                ret = self.db_proxy.query_one(table='surveys_collection', query={'company_id': company_id})
                log.debug('查询成功返回')
                return ret
        else:
            log.debug('查询失败返回')
            return deepcopy(g_ret)

        # email
        # invoice_id
        # user_id
        # company_guid
        # contacts
        # money fen
        # receive_addr
        # phone
        # order_no
        # date
        #
        # content_detail
        #
        # r_addr_phone
        # r_open_bank
        # r_tax_no
        # r_company_name
        #
        # s_addr_phone
        # s_open_bank
        # s_tax_no
        # s_company_name
        #

    def query_invoice_all(self, user_id):
        log.debug('查询用户发票: %s' % (user_id))
        ret = self.db_proxy.page_query(table='invoices_collection', query={'user_id': user_id})
        log.debug('用户发票查询结束')
        return ret

    def query_invoice_detail(self, invoice_id):
        log.debug('查询发票明细: %s' % (invoice_id))
        ret = self.db_proxy.query_one(table='invoices_collection', query={'invoice_id': invoice_id, 'del_flag': 0})
        log.debug('发票明细查询结束')
        return ret

    def invoice_add(self, question_id, setvalue, insert_not_found=False):
        log.debug('新增发票')
        invoice_id = str(uuid.uuid1()).replace("-", "")
        setvalue['invoice_id'] = invoice_id
        ret = self.db_proxy.insert(table='invoices_collection', value=setvalue)
        return ret

    def invoice_edit(self, invoice_id, setvalue, insert_not_found=False):
        log.debug('编辑发票')
        ret = self.db_proxy.update(table='invoices_collection', query={'invoice_id': invoice_id}, setvalue=setvalue,
                                   insert_not_found=insert_not_found)
        return ret

    def invoice_delete(self, invoice_id, insert_not_found=False):
        log.debug('删除发票: %s' % (invoice_id))
        setvalue = {}
        setvalue['invoice_id'] = invoice_id
        setvalue['del_flag'] = 1
        # ret = self.db_proxy.delete(table='invoices_collection', query={'invoice_id': invoice_id})
        ret = self.db_proxy.update(table='invoices_collection', query={'invoice_id': invoice_id}, setvalue=setvalue,
                                   insert_not_found=insert_not_found)
        return ret

    def query_payinfo_detail(self, trade_no):
        log.debug('查询支付单明细: %s' % (trade_no))
        ret = self.db_proxy.query_one(table='t_pay_info', query={'trade_no': trade_no})
        log.debug('支付单明细查询结束')
        return ret

    def pay_add(self, trade_no, setvalue, insert_not_found):
        log.debug('新增订单,后续支付记录')
        # out_trade_no 支付宝单号
        # rade_no 商品订单号-我们自己的订单号
        # total_amount 金额 10.0 表示10元,单位元
        ret = self.db_proxy.update(table='t_pay_info', query={'trade_no': trade_no}, setvalue=setvalue,
                                   insert_not_found=insert_not_found)
        ret['data'] = [{'trade_no': trade_no}]
        return ret

    def balance_recompute(self, tablename, aggreatelist):
        log.debug('余额重新计算')
        ret = self.db_proxy.aggregate(table=tablename, aggreatelist=aggreatelist)
        return ret

    def get_company(self, user_id):
        """
        根据user_id查询公司名称
        :param pagesize
        :param page
        :return:
        """
        log.debug('查询')
        log.debug('查询公司名称')
        user_item = self.db_proxy.query_one(table='t_user_product',
                                            query={'user_id': user_id, 'product_id': 'hr'})  # 获取公司名称或公司guid
        if user_item['count'] > 0:
            company_id = user_item['data'][0]['company_id']
            print('company_id=%s=' % company_id)
            companyname_item = self.db_proxy.query_one(table='company_collection', query={'guid': company_id})
            log.debug('按照GUID查询公司信息')
            log.debug('guid = %s' % company_id)
            print(companyname_item)
            if companyname_item.get('count') > 0:
                log.debug('查询成功返回')
                if companyname_item['data'][0].get('balance') is None or float(
                        companyname_item['data'][0].get('balance')) == 0:
                    companyname_item['data'][0]['balance'] = 0
                return companyname_item
            else:
                log.debug('无法按照GUID查询公司信息')
                companyname_item = self.db_proxy.query_one(table='company_collection',
                                                           query={'company_name': company_id})
                if companyname_item.get('count') > 0:
                    log.debug('查询成功返回')
                    if companyname_item['data'][0].get('balance') is None or float(
                            companyname_item['data'][0].get('balance')) == 0:
                        companyname_item['data'][0]['balance'] = 0
                    return companyname_item
                else:
                    log.debug('查询失败返回')
                    return deepcopy(g_ret)

    def upd_company_balance(self, company_guid, balance):
        """
        根据guid更新公司balance
        :param pagesize
        :param page
        :return:
        """
        log.debug('编辑公司余额信息')
        log.debug(company_guid)
        log.debug(balance)
        ret = self.db_proxy.update(table='company_collection', query={'guid': company_guid},
                                   setvalue={'guid': company_guid, 'balance': float(balance)},
                                   insert_not_found=False)
        return ret


hrPayinvoice = HRPayinvoice()


@app.route('/hrpay/query_invoice_all', methods=['GET', 'POST'])
@verify_token
def hrpay_query_invoice_all():
    '''
    返回:ret集合 ,ret.data=[]
    :return:
    '''
    log.debug(' ')
    param = get_param(request)
    g_user_id, ret = check_token(param.get('token'))
    # if param.get('token') == 'jim':
    #     g_user_id = 'test01'
    if g_user_id is None:
        return ret
    return json.dumps(hrPayinvoice.query_invoice_all(user_id=g_user_id))


@app.route('/hrpay/payback', methods=['GET', 'POST'])
def hrpay_payback():
    '''
    支付宝回调,支付成功,支付信息更改
    返回:ret集合 ,ret.data=[]
    :return:
    '''
    # collection: "t_pay_info"
    # {
    #     "_id": ObjectId,
    #     "user_id": String, // 用户id
    # "product_id": String, // 产品id，如: bole
    # "trade_no": String, // 订单号
    # "total_amount": Number, // 总金额
    # "pay_amount": Number, // 支付金额
    # "pay_status": Number, // 支付状态, 0 - 未支付，1 - 已支付，2 - 等待确认
    # "pay_type": Number, // 支付类型, 0 - 支付宝，1 - 微信，2 - 线下转账，3 - 其他
    # "pay_date": Number, // 支付时间
    # "remark": String // 订单备注
    # }
    log.debug('支付成功记录')
    param = get_param(request)
    paykey = param.get('pay_key')
    out_trade_no = param.get('out_trade_no')
    trade_no = param.get('trade_no')
    total_amount = float(param.get('total_amount'))
    setvalue = {}
    setvalue['out_trade_no'] = out_trade_no
    setvalue['trade_no'] = trade_no
    setvalue['pay_amount'] = float(total_amount)
    setvalue['pay_status'] = 1
    setvalue['pay_type'] = 0
    setvalue['pay_date'] = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
    if paykey != 'paybackhuayuan@8888':
        return json.dumps(deepcopy(g_ret))
    rettemp = hrPayinvoice.query_payinfo_detail(trade_no=out_trade_no)
    company_guid = rettemp['data'][0].get('company_guid')
    setvalue['company_guid'] = company_guid
    ret = hrPayinvoice.pay_add(setvalue=setvalue, trade_no=trade_no, insert_not_found=True)

    log.info(out_trade_no)
    log.info('=============get companyguid ===========')
    log.info(rettemp)
    aggreatelist = [
        {'$match': {'company_guid': company_guid}},
        {'$group': {'_id': '$company_guid', 'total': {'$sum': '$pay_amount'}}}
    ]
    balance_ret = hrPayinvoice.balance_recompute(tablename='t_pay_info', aggreatelist=aggreatelist)
    log.info(balance_ret)
    hrPayinvoice.upd_company_balance(balance_ret['data'][0]['_id'], balance_ret['data'][0]['total'])
    return json.dumps(ret)


@app.route('/hrpay/addpayorder', methods=['GET', 'POST'])
@verify_token
def hrpay_addpayorder():
    '''
    返回:ret集合 ,ret.data=[]
    :return:
    '''
    log.debug('新增准备支付订单记录')
    param = get_param(request)
    paykey = param.get('key')
    trade_no = ''
    if param.get('trade_no') is None:
        trade_no = "hr-" + str(uuid.uuid1()).replace("-", "")
    else:
        trade_no = param.get('trade_no')
    total_amount = float(param.get('total_amount'))
    pay_type = int(param.get('pay_type'))
    guid = param.get('guid')
    setvalue = {}
    setvalue['trade_no'] = trade_no
    setvalue['total_amount'] = float(total_amount)
    setvalue['pay_amount'] = 0
    setvalue['pay_status'] = 0
    setvalue['pay_type'] = pay_type
    setvalue['company_guid'] = guid
    setvalue['add_date'] = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
    setvalue['remark'] = ''
    url = "http://115.159.194.51:8093/order_pay?total_amount=" + str(total_amount) + "&order_no=" + trade_no
    setvalue['url'] = url
    addret = hrPayinvoice.pay_add(setvalue=setvalue, trade_no=trade_no, insert_not_found=True)
    addret['data'][0]['url'] = url
    return json.dumps(addret)


@app.route('/hrpay/get_company', methods=['GET', 'POST'])
@verify_token
def hrpay_get_company():
    log.debug('查询公司信息记录')
    param = get_param(request)
    g_user_id, ret = check_token(param.get('token'))
    if g_user_id is None:
        return ret
    return json.dumps(hrPayinvoice.get_company(user_id=g_user_id))


@app.route('/hrpay_upload', methods=['POST'])
def hrpay_upload():
    if request.method == 'POST':
        f = request.files['file']
        basepath = os.path.dirname(__file__)  # 当前文件所在路径
        newfilename = str(uuid.uuid4()).replace('-', '') + os.path.splitext(f.filename)[1]
        folder = time.strftime('%Y%m%d', time.localtime(time.time()))
        upload_path = basepath + '/../static/' + folder + '/' + newfilename
        if not os.path.exists(basepath + '/../static/' + folder):
            os.mkdir(basepath + '/../static/' + folder)
        abs_filename = 'static/' + folder + '/' + newfilename
        trade_no = request.form.get('trade_no')
        f.save(upload_path)
        f.close()
        ret = deepcopy(g_ret)
        ret['code'] = 200
        setvalue = {'trade_no': trade_no, 'filename': abs_filename}
        ret = hrPayinvoice.pay_add(setvalue=setvalue, trade_no=trade_no, insert_not_found=False)
        return json.dumps(ret)
